package geektime.spring.springbucks.waiter.controller;

import geektime.spring.springbucks.waiter.controller.request.NewOrderRequest;
import geektime.spring.springbucks.waiter.controller.request.UpdateOrDeleteCoffeeOrderRequest;
import geektime.spring.springbucks.waiter.model.Coffee;
import geektime.spring.springbucks.waiter.model.CoffeeOrder;
import geektime.spring.springbucks.waiter.service.CoffeeOrderService;
import geektime.spring.springbucks.waiter.service.CoffeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/order")
@Slf4j
public class CoffeeOrderController {
    @Autowired
    private CoffeeOrderService orderService;
    @Autowired
    private CoffeeService coffeeService;

    @GetMapping("/{id}")
    public CoffeeOrder getOrder(@PathVariable("id") Long id) {
        CoffeeOrder order = orderService.get(id);
        log.info("Get Order: {}", order);
        return order;
    }

    @PostMapping(path = "/", consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseStatus(HttpStatus.CREATED)
    public CoffeeOrder create(@RequestBody NewOrderRequest newOrder) {
        log.info("Receive new Order {}", newOrder);
        Coffee[] coffeeList = coffeeService.getCoffeeByName(newOrder.getItems())
                .toArray(new Coffee[] {});
        return orderService.createOrder(newOrder.getCustomer(), coffeeList);
    }

    /**
     * 更新订单的状态
     * @param request
     * @return
     */
    @PostMapping(path = "/updateOrderState", consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public boolean updateOrderState(@RequestBody UpdateOrDeleteCoffeeOrderRequest request) {
        log.info("update Order {}", request);
        CoffeeOrder order = orderService.get(request.getId());
        if (Objects.isNull(order)) {
            log.warn("order is not exist");
            return false;
        }
        return orderService.updateState(order,request.getState());
    }


    /**
     * 删除订单，未支付的订单可以删除
     * @param request
     * @return
     */
    @PostMapping(path = "/deleteOrder", consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public boolean deleteOrder(@RequestBody UpdateOrDeleteCoffeeOrderRequest request) {
        log.info("delete Order {}", request);
        CoffeeOrder order = orderService.get(request.getId());
        if (Objects.isNull(order)) {
            log.warn("order is not exist");
            return false;
        }
        return orderService.deleteOrder(order);
    }


}
